﻿#include "SplitDialog.h"
#include "DataTrans.h"
#include <QMessageBox>
#include <QCheckBox>
#include <QApplication>
#include <QClipboard>
#include <QFileDialog>
#include <QDateTime>
#include "xlsxwriter.h"

SplitDialog::SplitDialog(QWidget *parent)
	: QDialog(parent)
{
	ui.setupUi(this);	

	connect(ui.splitSetting, SIGNAL(sigSplitFinish()), this, SLOT(onSplitFinish()));

	//tableSplitLevel
	QStringList strListSplitLevel;
	strListSplitLevel << tr("级别") << tr("电池个数");
	UiHelper::SetTable(ui.tableSplitLevel, strListSplitLevel);

	//tableSplitList
	QStringList strListSplitList;
	strListSplitList << tr("序号") << tr("设备-单元-通道") << tr("放电容量(Ah)") << tr("放电时间（H:M:S:MS）")
		<< tr("中值电压（V）") << tr("级别") << tr("电池批号");
	UiHelper::SetTable(ui.tableSplitList, strListSplitList);
	ui.tableSplitList->horizontalHeader()->setSectionResizeMode(QHeaderView::Interactive);
}

SplitDialog::~SplitDialog()
{
}

void SplitDialog::showEvent(QShowEvent *event)
{	
	ui.splitSetting->init();
	ui.splitSetting->recordList = recordList;
	__super::showEvent(event);
}

void SplitDialog::onSplitFinish()
{
	auto split_ret = ui.splitSetting->result;
	if (split_ret.error)
	{
		QString tips = tr("分选失败 第%1条记录,无有效放电数据").arg(split_ret.erroNum);
		QMessageBox::information(this, "", tips);
		return;
	}
	ui.splitPie->setResult(split_ret);

	//总览
	auto range = ui.splitSetting->range();
	ui.tableSplitLevel->clearContents();
	ui.tableSplitLevel->setRowCount(16);
	int row = 0;
	for (int i = 0; i < 16; i++)
	{
		if (i == 15 || range[i].vaild)
		{
			QString name = (i < 15) ? QString('A' + i) : tr("落选");
							
			QTableWidgetItem *itemNumber = new QTableWidgetItem(QString::number(split_ret.indexs[i].size()));

			QCheckBox *itemNo = new QCheckBox(name);			
			itemNo->setProperty("level", i);
			itemNo->setChecked(true);
			connect(itemNo, SIGNAL(clicked()), this, SLOT(onSplitItemNo()));

			ui.tableSplitLevel->setCellWidget(row, 0, itemNo);
			ui.tableSplitLevel->setItem(row, 1, itemNumber);

			row++;
		}
	}
	ui.tableSplitLevel->setRowCount(row);	
	onSplitItemNo();	
}

void SplitDialog::onSplitItemNo()
{
	auto split_ret = ui.splitSetting->result;

	int idx = sender()->property("level").toInt();
	QVector<int> items;
	int count = ui.tableSplitLevel->rowCount();
	for (int i = 0; i < count; i++)
	{
		QCheckBox *box = (QCheckBox*)(ui.tableSplitLevel->cellWidget(i, 0));
		int level = box->property("level").toInt();
		if (box->isChecked())
			items << split_ret.indexs[level];
	}

	//update table
	ui.tableSplitList->clearContents();
	ui.tableSplitList->setRowCount(items.size());
	for (int i = 0; i < items.size(); i++)
	{
		int rec_idx = items[i];
		auto &info = split_ret.recordList[rec_idx];
		int item_idx = info.itemIndex;

		QTableWidgetItem *itemNo = new QTableWidgetItem(QString::number(i + 1));
		QTableWidgetItem *itemPos = new QTableWidgetItem(QString::number(item_idx / 8 + 1) + "-" + QString::number(item_idx % 8 + 1));
		QTableWidgetItem *itemCap = new QTableWidgetItem(QString::number(info.DisChargeCap));
		QTableWidgetItem *itemTime = new QTableWidgetItem(info.TimeText());
		QTableWidgetItem *itemVolt = new QTableWidgetItem(QString::number(info.MeanVoltage));
		QTableWidgetItem *itemLevel = new QTableWidgetItem(info.LevelText());
		QTableWidgetItem *itemCellNo = new QTableWidgetItem(info.CellNo);

		ui.tableSplitList->setItem(i, 0, itemNo);
		ui.tableSplitList->setItem(i, 1, itemPos);
		ui.tableSplitList->setItem(i, 2, itemCap);
		ui.tableSplitList->setItem(i, 3, itemTime);
		ui.tableSplitList->setItem(i, 4, itemVolt);
		ui.tableSplitList->setItem(i, 5, itemLevel);
		ui.tableSplitList->setItem(i, 6, itemCellNo);
	}	
}

void SplitDialog::on_btnSaveCopy_clicked()
{
    int count = ui.tableSplitList->rowCount();
    QVector<QStringList> text;
    QStringList head;
    head << tr("序号") << tr("设备-单元-通道") << tr("放电容量(Ah)") << tr("放电时间（H:M:S:MS）")
        << tr("中值电压（V）") << tr("级别") << tr("电池批号");

    text << head;
    for (int i = 0; i < count; i++)
    {
        QStringList line;
        for (int j = 0; j < 7; j++)
        {
            line << ui.tableSplitList->item(i, j)->text();
        }        
        text << line;
    }
    ExportSplitResult(this, text);
}

void ExportSplitResult(QWidget *w, QVector<QStringList> text)
{
    QString basename = "Split_" + QDateTime::currentDateTime().toString("yyyyMMdd_hhmmss") + ".xlsx";    
    QString filename = QFileDialog::getSaveFileName(w, "", basename, "*.xlsx");
    if (filename.isEmpty())
        return;

    lxw_workbook  *workbook = workbook_new(filename.toLocal8Bit().data());
    lxw_worksheet *sheet_detail = workbook_add_worksheet(workbook, "Sheet1");
    for (int i = 0; i < text.size(); i++)
    {
        for (int j = 0; j < text[i].size(); j++)
            worksheet_write_string(sheet_detail, i, j, qUtf8Printable(text[i][j]), NULL);
    }
    workbook_close(workbook);
}